package com.myplans.server.util.converter;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.log4j.Logger;

import com.myplans.shared.AndroidPlan;
import com.myplans.shared.Category;
import com.myplans.shared.User;
import com.myplans.vo.CategoryValue;
import com.myplans.vo.PlanValue;
import com.myplans.vo.UserValue;


public class AndroidPlanConverter implements Converter {

	private static Logger logger = Logger.getLogger(AndroidPlanConverter.class);

	@SuppressWarnings("rawtypes")
	@Override
	public Object convert(Class type, Object value) throws ConversionException {

		if (value instanceof AndroidPlan) {
			PlanValue planValue = new PlanValue();
			try {
				BeanUtils.copyProperties(planValue, value);
				UserValue userValue = new UserValue();
				AndroidPlan plan = (AndroidPlan) value;
				BeanUtils.copyProperties(userValue, plan.getUser());
				planValue.setUser(userValue);
				if (plan.getCategory() != null) {
					CategoryValue categoryValue = new CategoryValue();
					BeanUtils.copyProperties(categoryValue, plan.getCategory());
					planValue.setCategory(categoryValue);
				}
			} catch (IllegalAccessException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			}
			return planValue;
		} else if (value instanceof PlanValue) {
			AndroidPlan plan = new AndroidPlan();
			try {
				BeanUtils.copyProperties(plan, value);
				User user = new User();
				PlanValue planValue = (PlanValue)value;
				BeanUtils.copyProperties(user, planValue.getUser());
				plan.setUser(user);
				if (planValue.getCategory() != null) {
					Category category = new Category();
					BeanUtils.copyProperties(category, planValue.getCategory());
					plan.setCategory(category);
				}
			} catch (IllegalAccessException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			}
			return plan;
		}

		logger.debug("Returning a null value, possibly a conversion error.");
		return null;
	}
}
